package com.brillilab.starter.controller.aio.lab;

import com.alibaba.fastjson.JSONObject;
import com.brillilab.common.constant.ClientTypeEnum;
import com.brillilab.common.constant.KeyProfixConstant;
import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.entity.ResponseVo;
import com.brillilab.common.redis.RedisCache;
import com.brillilab.common.utils.CodeUtil;
import com.brillilab.common.utils.MyBeanUtils;
import com.brillilab.domain.enums.kit.KitEnum.Classify;
import com.brillilab.domain.enums.lab.LabMemberEnum;
import com.brillilab.domain.enums.lab.UserEnum;
import com.brillilab.domain.po.lab.Lab;
import com.brillilab.domain.po.lab.LabDevice;
import com.brillilab.domain.po.user.Users;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.core.experiments.IExperimentService;
import com.brillilab.service.core.kit.IKitService;
import com.brillilab.service.core.lab.ILabDeviceService;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.lab.ILabService;
import com.brillilab.service.core.method.IMethodLabViewService;
import com.brillilab.service.core.topics.ITopicService;
import com.brillilab.service.core.user.IUsersService;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.starter.aspect.AspectLog;
import com.brillilab.starter.constant.StarterConstant;
import com.brillilab.starter.entity.resp.lab.LabInfoResp;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * 实验室API
 *
 * @author lj
 */
@RestController
@RequestMapping("/api/lab")
public class LabController {

	@Resource
	private ILabService labService;
	@Resource
	private ILabDeviceService labDeviceService;
	@Resource
	private UsersLogic usersLogic;
	@Resource
	private ILabMemberService labMemberService;
	@Resource
	private IKitService kitService;
	@Resource
	private IMethodLabViewService methodLabViewService;
	@Resource
	private IExperimentService experimentService;
	@Resource
	private ITopicService topicService;
	@Resource
	private IUsersService usersService;

	@Resource
	private RedisCache redisCache;

	/**
	 * 实验室信息
	 *
	 * @return
	 */
	@PostMapping("/info")
//	@RequestPower(LabMemberPowerEnum.order_receive) // 权限注解
	public ResponseVo getInfo(@RequestHeader(name = StarterConstant.TOKEN) String token) {

		Assert.isTrue(!StringUtils.isBlank(token), "请求参数缺失！");

		UserInfoVo userInfo = usersLogic.getUserByToken(token);

		Lab lab = labService.selectById(userInfo.getLabId());
		if (lab != null) {
			LabInfoResp infoResp = MyBeanUtils.copyBean(lab, LabInfoResp.class);
			infoResp.setLabId(lab.getId());

			Users user = usersLogic.getUser(lab.getOwnerId());
			if (user != null) {
				infoResp.setOwnerName(user.getName());
			}
			// 调试剂接口获取试剂总数
			infoResp.setReagentCount(kitService.selectKitCount(lab.getId()));

			// 查询成员数量
			Integer count = labMemberService.selectCount(lab.getId(), LabMemberEnum.State.STATE_IN.getValue());
			infoResp.setMemberCount(count);
			if (StringUtils.isEmpty(infoResp.getImageUrl())) {
				//若实验室logo为空,返回默认头像
				infoResp.setImageUrl("https://labinone-public.oss-cn-hangzhou.aliyuncs.com/image/default/lab_default.png");
			}

			return ResponseVo.success(infoResp);
		}
		return ResponseVo.failure();
	}

	/**
	 * 获取实验室设备关系信息 {\"deviceNo\":\"设备编号必填S\"}
	 *
	 * @return
	 */
	@PostMapping("/device")
	public ResponseVo getDevice(@RequestBody JSONObject json) {
		String deviceNo = json.getString("deviceNo");
		if (StringUtils.isBlank(deviceNo)) {
			return ResponseVo.failure(ResultEnum.REQUEST_PARAM_LACK);
		}
		LabDevice ldrs = labDeviceService.selectByNo(deviceNo);
		if (ldrs != null) {
			Lab lrs = labService.selectById(ldrs.getLabId());
			LabInfoResp labInfo = MyBeanUtils.copyBean(lrs, LabInfoResp.class);
			labInfo.setLabId(lrs.getId());

			// 查询成员数量
			Integer count = labMemberService.selectCount(lrs.getId(), LabMemberEnum.State.STATE_IN.getValue());
			labInfo.setMemberCount(count);

			return ResponseVo.success(labInfo);
		}
		return ResponseVo.failure();

	}

	/**
	 * 获取实验一体机室设备列表
	 * 
	 * @param state 状态：0-未绑定，1-已绑定，2-停用，null-全部
	 * @return
	 */
	@GetMapping("/devicelist")
	public ResponseVo getDeviceList(@RequestHeader(name = StarterConstant.TOKEN) String token, Integer state) {
		UserInfoVo userInfo = usersLogic.getUserByToken(token);
		return ResponseVo.success(labDeviceService.selectList(userInfo.getLabId(), state));

	}

	/**
	 * 一体机机器登录
	 * 
	 * @param labId
	 * @param deviceNo
	 * @return
	 */
	@RequestMapping(value = "/aio/login", method = RequestMethod.POST)
	public ResponseVo aioLogin(Long labId, String deviceNo) {
		Assert.isTrue(labId != null && StringUtils.isNotBlank(deviceNo), "请求参数缺失！");

		LabDevice labDevice = labDeviceService.selectByNo(deviceNo);
		Assert.notNull(labDevice, "一体机编号不存在！");
		Assert.isTrue(labDevice.getLabId().equals(labId), "一体机不属于该实验室！");

		String token = CodeUtil.getToken(ClientTypeEnum.SOCKET);
		redisCache.set(KeyProfixConstant.TOKEN + token, labDevice);

		HashMap<String, String> result = new HashMap<>();
		result.put("token", token);

		return ResponseVo.success(token);
	}

	/**
	 * 实验室数据统计
	 * 
	 * @return
	 */
	@RequestMapping(value = "/data/statistics", method = RequestMethod.GET)
	public ResponseVo dataStatistics(@RequestHeader(name = StarterConstant.TOKEN) String token) {
		UserInfoVo userInfo = usersLogic.getUserByToken(token);
		Integer memberNum = labMemberService.selectCount(userInfo.getLabId(), LabMemberEnum.State.STATE_IN.getValue());
		int reagentNum = kitService.getKitCount(userInfo.getLabId(), Classify.REAGENT);
		int sampleNum = kitService.getKitCount(userInfo.getLabId(), Classify.SAMPLE);
		int methodNum = methodLabViewService.getMethodCount(userInfo.getLabId());
		int experimentNum = experimentService.getExperimentCount(userInfo.getLabId());
		int topicNum = topicService.getTopicCount(userInfo.getLabId());
		
		HashMap<String, Integer> result = new HashMap<>();
		result.put("memberNum", memberNum);
		result.put("reagentNum", reagentNum);
		result.put("sampleNum", sampleNum);
		result.put("methodNum", methodNum);
		result.put("experimentNum", experimentNum);
		result.put("topicNum", topicNum);
		return ResponseVo.success(result);
	}
	
	
	/**
	 * 添加实验室
	 * 
	 * @return
	 */
	@AspectLog
	@RequestMapping(value = "/addLab", method = RequestMethod.GET)
	public ResponseVo addLab(String labName, String mobile) {
		
		Assert.isTrue(StringUtils.isNotBlank(labName) && StringUtils.isNotBlank(mobile) , "请求参数缺失！");
		
		Users user = usersService.selectUser(mobile,UserEnum.State.NORMAL.getValue());
		Assert.isTrue(user == null, "手机号码已被注册！");
		Lab lab = new Lab();
		lab.setName(labName);
		lab.setState(UserEnum.State.NORMAL.getValue());
		lab.setOrgName(labName+"机构");
		lab.setAcademy(labName+"学院");
		lab.setOwnerId(0L);
		lab = labService.insert(lab);
		
		// 用户注册
		user = usersLogic.userRegister(lab.getId(), mobile, "123asd", mobile, "教授", new Date(), "123456789");
		lab.setOwnerId(user.getId());
		labService.updateById(lab);

		return ResponseVo.success(user);
	}

//	@RequestMapping(value="/expire",method=RequestMethod.GET)
//	public ResponseVo createLabExpireJobs(@RequestHeader(value=StarterConstant.TOKEN) String token){
//		UserInfoVo userInfo=usersLogic.getUserByToken(token);
//		Lab lab=labService.selectById(userInfo.getLabId());
//		labService.createLabExpireJobs(lab);
//		return ResponseVo.success();
//	}

}
